<?php
namespace app\index\controller;
use think\Controller;
use app\index\model\User as UserModel;
use app\index\model\Msg;
use think\Loader;
use think\Db;

class User extends Common
{
    public function index()
    {

        $uid = input('uid');

        $user = UserModel::get($uid);

        $this->assign('user',$user);
        
        $this->assign('title',$user->nickname."个人中心");
        
        return $this->fetch();
    }

    public function set()
    {
        $user = UserModel::get(session('uid'));

        $this->assign('user',$user);

        $this->assign('title',"用户设置中心");

        return $this->fetch();
    }

    public function setpost()
    {
        $data = input('post.');

        $data['uid'] = session('uid');

        $validate = Loader::validate('set');

        if(!$validate->check($data)){
            
            $this->error($validate->getError());
        }

       // todo::更新数据 
       
       // Db::table('fly_user')->where('uid', session('uid'))->update( $data);

        $res = (new UserModel)->save($data,['uid' => session('uid')]);

        if($res===false){
            $this->error('保存失败');
        }else{
            $this->success('保存成功');
        }
    }

    public function upload()
    {

        if(isset($_FILES['meitu'])){
            $is_meitu  = true;
            $file = request()->file('meitu');
        }else{
            $is_meitu  = false;
            $file = request()->file('file');
        }

        // 移动到框架应用根目录/public/uploads/ 目录下
        if($file){

            $info = $file->validate(['size'=>500000,'ext'=>'jpg,png,gif'])->move('./uploads');

            if($info){
                
                $face ='uploads/'.date("Ymd").'/'.$info->getFilename();
                // todo::更新数据 
                // 
                $res = (new UserModel)->save(['face'=>$face],['uid' => session('uid')]);

                unlink(session('face'));

                session('face',$face);

                if($res===false){

                    $this->error('保存失败');

                }else{
                    if($is_meitu){
                        echo 'ok';
                        exit;
                    }else{
                        $this->success('保存成功');
                    }
                }

            }else{

                $this->error($file->getError());
                // 上传失败获取错误信息
            }
        }else{
            $this->error('上传失败');
        }
    }


    public function question()
    {
        $this->assign('title',"我的帖子");
        return $this->fetch();
    }

    public function msg()
    {

        $msgs= Db::table('fly_msg')
            ->alias('t1')
            ->join('fly_question t2','t1.qid=t2.qid')
            ->join('fly_user t3','t1.suid=t3.uid')
            ->field('t1.*,t2.title,t3.nickname')
            ->where(['t1.duid'=>session('uid')])
            ->select();
        $this->assign('msgs',$msgs);
        return $this->fetch();
    }

}
